const base = {}


base.sendAjaxRequest = (method, url, body=null, file=null) => {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open(method, url);

        xhr.responseType = 'json';

        setHeaders(xhr, body, file);
        xhr.onload = () => resolve(xhr.response)
        sendResponse(xhr)
    })


    // НИЖЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

    function sendResponse(xhr) {
        if (body) {
            xhr.send(JSON.stringify(body));
        } else if(file) {
            const formData = new FormData();
            formData.append('file', file.fileData, file.fileName);
            xhr.send(formData);
        } else {
            xhr.send();
        }
    }

    function setHeaders(xhr, body, file) {
        // Устанавливаем заголовки
        
        if(body) {
            xhr.setRequestHeader('X-CSRFToken', body.token);
            xhr.setRequestHeader('Content-Type', 'application/json');
        } else if(file) {
            xhr.setRequestHeader('X-CSRFToken', file.token);
        }
    }
}


base.clearListOfPeople = () => {
    // Очищаем список людей
    const element = document.querySelector('.list-of-people .content-list-of-people');
    if (element) element.innerHTML = '';
}


base.clearWrittingArea = () => {
    // Очищаем поле для письма
    document.querySelector('.form-of-sending-letter textarea').value = '';
};


base.notifyAboutSomething = (htmlToInsert, deleteMessage=false, deleteNotification=false) => {
    // Уведомляем о чем-то

    const notifyAboutSomething = document.querySelector('.notify-about-something')
    notifyAboutSomething.innerHTML = htmlToInsert;

    if (deleteMessage) base.clearWrittingArea();
    if (deleteNotification) {
            setTimeout(() => {
            notifyAboutSomething.innerHTML = '';
        }, 2000)
    };
}


base.selectMessageRecipients = (basicInformation=false) => {
    // Делаем выборку получателей

    let recipients = document.querySelectorAll('[data-selected-by-recipient="true"]');
    if (!basicInformation) return recipients;

    let count = 0
    let result = {}
    Array.from(recipients).forEach(element => {
        let recipients = element.getAttribute('data-information-about-person');
        const fullName = element.innerHTML;
        const [id, birthday, email] = recipients.split(' ');
        recipients = {'id': id, 'birthday': birthday, 'email': email, 'fullName': fullName};
        result[count] = recipients;
        count += 1;
    });
    return result
}

base.removeSelectionOfSelectedPeople = () => {
    // Убираем выделение у выбранных людей
    document.querySelectorAll('[data-selected-by-recipient]').forEach(item => {
        item.style.background = ''
    })
}

base.clearListOfAllMessages = () => {
    // Очищаем список всех сообщений
    document.querySelector('.content-list-of-people').innerHTML = '';
}